let webSocket;
const app = getApp();
export default {
  /**
   * 链接服务器
   * @param {用户id}} userId 
   */
  connectServer(userId) {
    userId=userId || app.globalData.myUserInfo.id
    wx.showLoading({
      title: '连接服务器中...',
    })
    console.log("websocket>>>" + userId)
    wx.connectSocket({
      url: app.globalData.WEB_SOCKET_ADDRESS.concat(userId),
    })
    /**
     * 链接成功
     */
    wx.onSocketOpen((result) => {
      wx.event.emit("socket-events",{"msg":"connected"})
      wx.onSocketMessage((result) => {
        wx.hideLoading({
          complete: (res) => {},
        })
        var data = JSON.parse(result.data);
        if(data instanceof Array){
          data.forEach((item)=>{
            this.releaseMessage(item)
          })
        }else{
            this.releaseMessage(data)
        }
      

      })
    })
    wx.onSocketClose((result) => {
      wx.hideLoading({
        complete: (res) => {},
      })
      wx.event.emit("socket-events",{"msg":"close"})

      console.log("WebSocket关闭")
    })
    wx.onSocketError((result) => {
      wx.hideLoading({
        complete: (res) => {},
      })
      wx.event.emit("socket-events",{"msg":"close"})

      console.log("WebSocketc错误")
    })
  },
  releaseMessage(message){
    switch (message.action) {
      case 2:
        wx.event.emit('system-message', message)
        break;
      case 1:
        wx.event.emit('receive-message', message)
        break
    }
  },
  sendMessage(message) {
    wx.sendSocketMessage({
      data: JSON.stringify(message),
    })
  },
  recvMessage() {
    wx.onSocketMessage((result) => { })
  }
}